﻿// Defines the dynamic grid view for the desktop

Ext.define('App.desktop.GridView', {
    extend: 'Ext.grid.Panel',
    requires: [
            'Ext.data.StoreManager',
            'Ext.ModelManager',
            'Ext.data.Model',
            'Ext.util.Grouper',
            'App.desktop.Workspace'
        ],
    alias: 'widget.GridView',
    loadMask: false, // We will handle the mask
    entity: null,
    pageSize: 25,

    initComponent: function () {

        var me = this;

        me.store = me.createStore();
        me.columns = me.createColumns();
        me.dockedItems = me.createToolbars();
        me.bbar = me.createPagingToolbar();
        me.gridMenu = me.createGridMenu();

        me.listeners =
        {
            beforeitemcontextmenu: function (view, record, item, index, e) {

                e.stopEvent();

                me.selModel.select(index); // Select the row
                me.gridMenu.showAt(e.getXY());
            },
            itemdblclick: function (view, record, item, index, e, eOpts) {

                me.selModel.select(index); // Select the row
                me.editEntity(); // TODO: Setting to maybe view entity on doubleclick
            }
        };

        App.desktop.Workspace.createOpeners(me.entity);

        me.callParent();
    },

    createStore: function () {

        var me = this;
        var workspace = App.desktop.Workspace;
        var fields = [];

        var entity = me.child || me.entity;

        var attributeName = null;
        var url = '/Entity/GetCollection';

        if (me.attribute) {

            attributeName = me.attribute.Name;
            url = '/Entity/GetCollectionAttribute';
        }

        Ext.each(entity.Attributes, function (a, i) {

            fields.push({
                name: a.Name,
                type: workspace.getType(a.Type),
                mapping: 'fields.' + a.Name
            });

        }, me);

        return Ext.create('Ext.data.Store', {
            fields: fields,
            pageSize: me.pageSize,
            proxy:
            {
                type: 'ajax',
                url: url,
                extraParams:
                {
                    typeName: me.entity.FullName,
                    attributeName: attributeName,
                    identifiers: me.identifiers
                },
                reader:
                {
                    type: 'json',
                    root: 'data',
                    totalProperty: 'count'
                },
                listeners:
                {
                    exception: function (proxy, response, operation) {

                        var msg = operation.getError() || Ext.decode(response.responseText).msg;

                        if (msg == 'Session expired') { // Log out the user if the session expired

                            App.desktop.Workspace.logOff();
                            return;
                        }

                        workspace.showError('Error', msg);
                    }
                }
            }
        });
    },

    createColumns: function () {

        var me = this;
        var workspace = App.desktop.Workspace;
        var columns = [];

        var entity = me.child || me.entity;

        Ext.each(entity.Attributes, function (a, i) {

            var type = workspace.getType(a.Category);

            switch (type) {

                case 'complex':
                    {
                        columns.push({
                            text: a.Name,
                            dataIndex: a.Name,

                            renderer: function (value, metaData, record, rowIndex, colIndex, store) {

                                var parentId = Ext.encode(record.raw.identifiers);
                                parentId = parentId.replace(/["']{1}/gi, "");

                                var link = '<a href="javascript:void(0)" onclick="App.desktop.Workspace.openWindow(\'' + me.entity.FullName + '\',\'' + a.Name + '\',' + parentId + ');"><img src="Content/Icons/application_form.png" class="icon-center"></a>';

                                return link;
                            }
                        });
                    }
                    break;
                case 'collection': // The image is different
                    {
                        columns.push({
                            text: a.Name,
                            dataIndex: a.Name,

                            renderer: function (value, metaData, record, rowIndex, colIndex, store) {

                                var parentId = Ext.encode(record.raw.identifiers);
                                parentId = parentId.replace(/["']{1}/gi, "");

                                var link = '<a href="javascript:void(0)" onclick="App.desktop.Workspace.openWindow(\'' + me.entity.FullName + '\',\'' + a.Name + '\',' + parentId + ');"><img src="Content/Icons/table.png" class="icon-center"></a>';

                                return link;
                            }
                        });
                    }
                    break;
                default:
                    {
                        columns.push({
                            text: a.Name,
                            dataIndex: a.Name
                        });
                    }
                    break;
            }

        }, this);

        return columns;
    },

    createToolbars: function () {

        var me = this;

        return [
            {
                xtype: 'toolbar',
                items: [
                    {
                        itemId: 'add',
                        text: 'Add',
                        iconCls: 'icon-add',
                        handler: me.addEntity,
                        scope: this
                    }
                ]
            }
        ];
    },

    createPagingToolbar: function () {

        return Ext.create('Ext.PagingToolbar', {
            itemId: 'pager',
            store: this.store,
            pageSize: this.pageSize,
            displayInfo: true,
            displayMsg: 'Displaying record {0} - {1} of {2}',
            emptyMsg: "No topics to display",
            items: []
        });
    },

    createGridMenu: function () {

        var menu = Ext.create('Ext.menu.Menu', {
            items: [
                {
                    text: 'View',
                    iconCls: 'icon-view',
                    handler: this.viewEntity,
                    scope: this
                },
                {
                    text: 'Edit',
                    iconCls: 'icon-edit',
                    handler: this.editEntity,
                    scope: this
                },
                {
                    text: 'Delete',
                    iconCls: 'icon-delete',
                    handler: this.deleteEntity,
                    scope: this
                }
            ]
        });

        return menu;
    },

    addEntity: function () {

        var me = this;

        App.desktop.Workspace.openDetailWindow(me.window, {
            operation: 'add',
            entity: me.entity,
            callback: function () {

                me.refreshPage();
            }
        });
    },

    viewEntity: function () {

        var me = this;
        var sel = me.selModel.getSelection()[0];

        App.desktop.Workspace.openDetailWindow(me.window, {
            operation: 'view',
            entity: me.entity,
            identifiers: sel.raw.identifiers
        });
    },

    editEntity: function () {

        var me = this;
        var sel = me.selModel.getSelection()[0];

        App.desktop.Workspace.openDetailWindow(me.window, {
            operation: 'edit',
            entity: me.entity,
            identifiers: sel.raw.identifiers,
            callback: function () {

                me.refreshPage();
            }
        });
    },

    deleteEntity: function () {

        var me = this;
        var sel = me.selModel.getSelection()[0];

        Ext.application.Desktop.deleteEntity(this.entity, sel.raw.identifiers, function () {

            me.refreshPage();
            //me.getComponent('pager').moveFirst(); // It refreshes the grid and moves it ot the first page, to avoid tracking a page that might not exist anymore after deleting the itme
        });
    },

    // Refreshes the current page
    refreshPage: function () {

        this.getComponent('pager').doRefresh();
    },

    loadGrid: function () {

        var me = this;
        var el = me.el;

        el.mask({ msg: 'Loading ...' });

        me.store.load({
            params:
            {
                start: 0,
                limit: me.pageSize
            },
            callback: function () {
                el.unmask();
            }
        });
    }
});